<template>
  <div class="user-search">
    <el-form :inline="true" :model="queryInfo" class="form-inline">
      <el-form-item label="咨询师名">
        <el-input v-model="queryInfo.name" placeholder="请输入用户名" style="width: 170px;" clearable />
      </el-form-item>
      <el-form-item label="性别">
        <el-select v-model="queryInfo.sex" placeholder="选择性别" style="margin-left: 30px; width: 100px;">
          <el-option label="男" value="M" />
          <el-option label="女" value="F" />
        </el-select>
      </el-form-item>
      <el-form-item label="等级">
        <el-select v-model="queryInfo.levelId" placeholder="选择等级" style="margin-left: 30px; width: 100px;">
          <el-option label="全部" value="0" />
          <el-option label="一级" value="1" />
          <el-option label="二级" value="2" />
          <el-option label="三级" value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否认证">
        <el-select v-model="queryInfo.authentication" placeholder="请选择" style="width: 100px;">
          <el-option label="全部" value="0" />
          <el-option label="未认证" value="1" />
          <el-option label="已认证" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getList">搜索</el-button>
        <el-button icon="Delete" @click="reset()">重置</el-button>
        <el-button type="primary" icon="CirclePlusFilled" @click="addForm()">添加</el-button>
      </el-form-item>
    </el-form>
  </div>
  <div class="user-table">
    <el-table :data="tableData" style="width: 1200px; overflow-x: auto !important; margin: 0 auto;">
      <el-table-column label="序号" width="50">
        <template #default="{ $index }">
          {{ $index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="name" label="咨询师名" width="100"/>
      <el-table-column prop="sex" label="性别" width="80">
        <template #default="scope">
          <span v-if="scope.row.sex=='F'">女</span>
          <span v-if="scope.row.sex=='M'">男</span>
        </template>
      </el-table-column>
      <el-table-column prop="levelId" label="咨询师等级" width="100">
        <template #default="scope">
          <el-tag v-if="scope.row.levelId==1">一级</el-tag>
          <el-tag v-if="scope.row.levelId==2">二级</el-tag>
          <el-tag v-if="scope.row.levelId==3">三级</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="tabularChart" label="图片" width="110">
        <template #default="scope">
          <el-image v-if="scope.row.img" :src="url + scope.row.img" alt="" style="width: 100px; height: 100px;"/>
        </template>
      </el-table-column>
      <el-table-column prop="address" label="地址"  width="90">
        <template #default="scope">
          <el-button @click="showDetail(1, scope.row)" type="primary" link style="margin-left: 5px;">
            <el-icon>
              <Help />
            </el-icon>
            详情
          </el-button>
        </template>
      </el-table-column>
      <el-table-column prop="intro" label="介绍"  width="90">
        <template #default="scope">
          <el-button @click="showDetail(2, scope.row)" type="primary" link >
            <el-icon>
              <Help />
            </el-icon>
            详情
          </el-button>
        </template>
      </el-table-column>
      <el-table-column prop="authentication" label="是否认证" width="100">
        <template #default="scope">
          <el-tag type="danger" v-if="scope.row.authentication==1">未认证</el-tag>
          <el-tag type="success" v-if="scope.row.authentication==2">已认证</el-tag>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="modify(scope.row)">
            修改
          </el-button><br/>
          <el-button link type="primary" icon="Delete" @click="del(scope.$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      style="width: 1200px; margin: 20px auto 0 auto;"
      v-model:current-page="queryInfo.pageNum"
      v-model:page-size="queryInfo.pageSize"
      :page-sizes="[3, 5, 10, 20]"
      size="default"
      background="background"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalNum"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>

  <el-dialog 
    v-model="addFormVisible" 
    :title="dialogType==0?'添加':'修改'" 
    width="500"
    @close="cancel"
  >
    <el-form :model="consultInfor">
      <el-form-item label="咨询师名称">
        <el-input v-model="consultInfor.name" placeholder="输入用户名称" autocomplete="off" />
      </el-form-item>
      <el-form-item label="咨询师性别">
        <el-select v-model="consultInfor.sex" placeholder="选择性别" style="width: 100px;">
          <el-option label="男" value="M" />
          <el-option label="女" value="F" />
        </el-select>
      </el-form-item>
      <el-form-item label="咨询师等级">
        <el-select v-model="consultInfor.levelId" placeholder="选择性别" style="width: 100px;">
          <el-option label="一级" value="1" />
          <el-option label="二级" value="2" />
          <el-option label="三级" value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="照片" :label-width="formLabelWidth">
        <el-upload
          style="margin-left: 43px;"
          v-model:file-list="fileList"
          class="avatar-uploader"
          list-type="picture-card"
          action="http://localhost/file/upload"
          :on-success="handleAvatarSuccess"
        >
          <img v-if="!fileList" :src="imageUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="咨询师地址">
        <quill-editor v-model:value="consultInfor.address" />
      </el-form-item>
      <el-form-item label="咨询师简介" v-if="detailType === 2">
        <quill-editor v-model:value="consultInfor.intro" />
      </el-form-item>
      <el-form-item label="是否认证">
        <el-select v-model="consultInfor.authentication" placeholder="请选择" style="margin-left: 15px; width: 100px;">
          <el-option label="未认证" value="1" />
          <el-option label="已认证" value="2" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancel2">取消</el-button>
        <el-button type="primary" @click="addOrModifyInfor()">
          {{ dialogType==0?'添加':'修改' }}
        </el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog 
    v-model="detailVisible" 
    :title="detailType === 1 ? '咨询师地址' : '咨询师简介'" 
    width="500"
    @close="closeDetail"
  >
    <el-form :model="consultInfor">
      <el-form-item v-if="detailType === 1" label="咨询师地址">
        <quill-editor v-model:value="consultInfor.address" />
      </el-form-item>
      <el-form-item v-if="detailType === 2" label="咨询师简介">
        <quill-editor v-model:value="consultInfor.intro" />
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import QuillEditor from '@/components/QuillEditor.vue';

const addFormVisible = ref(false)
const detailVisible = ref(false)
const totalNum = ref(0);
const dialogType = ref(0);
const url = ref("http://localhost/file/downLoad?fileName=");
const detailType = ref(0); // 新增 detailType 变量

// 定义一个方法当页面加载后立马执行的代码
onMounted(() => {
  getList();
})

// 定义一个全局的查询参数变量
const queryInfo = ref({
  pageNum: '',
  pageSize: 5,
  name: '',
  sex: '',
  levelId: 0,
  authentication: 0,
})

// 重置并刷新
function reset() {
  queryInfo.value.name = '';
  queryInfo.value.sex = '';
  queryInfo.value.levelId = 0;
  queryInfo.value.authentication = 0;
  getList();
}

// 定义一个方法，当页码发生变化时，调用后端接口，获取文章列表
const handleCurrentChange = (val) => {
  queryInfo.value.pageNum = val;
  getList();
}

// 定义一个方法，当每页显示的条数发生变化时，调用后端接口，获取文章列表
const handleSizeChange = (val) => {
  queryInfo.value.pageSize = val;
  queryInfo.value.pageNum = 1;
  getList(); 
}

// 定义一个方法，来动态的调用后端接口，获取文章列表
const getList = () => {
  axios.get('/consult/findAll', {
    params: queryInfo.value
  })
  .then(resp => {
    console.log(resp.data);
    let result = resp.data;
    if (result.code == 1) {
      tableData.value = result.data.list;  
      totalNum.value = result.data.total;
    } else {
      console.log('获取文章列表失败');
    }
  })
}

const tableData = ref([
  {
    id: '',
    name: '',
    sex: '',
    levelId: 0,
    img: '',
    address: '',
    intro: '',
    authentication: 0,
  }
])

const consultInfor = ref({
  id: '',
  name: '',
  sex: '',
  levelId: 0,
  img: '',
  address: '',
  intro: '',
  authentication: 0,
})

const fileList = ref([]);
const imageUrl = ref('');
const delUrl = ref('');

const handleAvatarSuccess = (response, uploadFile) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw);
  delUrl.value = response.data;
  consultInfor.value.img = response.data;
}

function addForm() {
  dialogType.value = 0;
  consultInfor.value.name = '';
  consultInfor.value.sex = '';
  consultInfor.value.levelId = 0;
  consultInfor.value.img = '';
  consultInfor.value.address = ' ';
  consultInfor.value.intro = ' ';
  consultInfor.value.authentication = 0;
  addFormVisible.value = true;
}

function modify(row) {
  dialogType.value = 1;
  consultInfor.value = row;
  addFormVisible.value = true;
  if (consultInfor.value.img === '' || consultInfor.value.img === null) {
    fileList.value = [];
  } else {
    fileList.value = [{
      name: consultInfor.value.img,
      url: url.value + consultInfor.value.img
    }];
  }
}

function addOrModifyInfor() {
  if (dialogType.value == 0) {
    axios.post('/consult/add', consultInfor.value)
    .then(resp => {
      let result = resp.data;
      if (result.code == 1) {
        getList(); 
      } else {
        console.log('添加文章失败')
      }
    })
  } else {
    axios.put('/consult/update', consultInfor.value)
    .then(resp => {
      let result = resp.data;
      if (result.code == 1) {
        getList(); 
      } else {
        console.log('修改文章失败') 
      }
    })
  }

  consultInfor.value = {
    id: 0,
    name: '',
    sex: '',
    levelId: 0,
    img: '',
    address: '',
    intro: '',
    authentication: 0,
  }
  addFormVisible.value = false;
}

function delImgInPan() {
  console.log(delUrl.value);
  axios.delete('http://localhost/file/delete', { params: { fileName: delUrl.value } })
}

function cancel2() {
  delImgInPan();
  addFormVisible.value = false;
}

function cancel() {
  getList();
  consultInfor.value = {
    id: 0,
    name: '',
    sex: '',
    levelId: 0,
    img: '',
    address: '',
    intro: '',
    authentication: 0,
  }
  fileList.value = [];
  imageUrl.value = '';
}

function del(n) {
  let id = tableData.value[n].id;
  delUrl.value = tableData.value[n].img;
  ElMessageBox.confirm(
    '你确定要删除吗？',
    '确定',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      center: true,
    }
  )
  .then(() => {
    axios.delete('/consult/' + id)
    .then(resp => {
      let result = resp.data;
      if (result.code == 1) {
        delImgInPan();  // 删除图片
        getList(); 
        ElMessage({
          message: '删除成功！',
          type: 'success',
        })
      } else {
        ElMessage({
          message: '删除失败！',
          type: 'warning',
        })
      }
    })
  })
  .catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消',
    })
  })
}

function showDetail(n, row) {
  detailType.value = n;
  consultInfor.value = row;
  detailVisible.value = true;
}

function closeDetail() {
  detailVisible.value = false;
}
</script>

<style scoped>
.user-search { width: 800px; margin: 30px auto; }
.user-table { z-index: 0; position: relative; }

.avatar-uploader .el-upload {
  border: 1px dashed black;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 160px;
  height: 160px;
  text-align: center;
}

.avatar-uploader .avatar {
  width: 160px;
  height: 160px;
  display: block;
}
</style>